package com.boot.app.file.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.boot.api.ApiResult;
import com.boot.app.file.domain.FileAttach;
import com.boot.app.file.service.IFileAttachService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@RestController
@RequestMapping("file/attach")
public class FileAttachController {

    private final IFileAttachService attachService;

    @Autowired
    public FileAttachController(IFileAttachService attachService){
        this.attachService = attachService;
    }

    @GetMapping("list/{groupId}")
    public ApiResult<List<FileAttach>> getAttachListByGroupId(@PathVariable long groupId){
        LambdaQueryWrapper<FileAttach> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileAttach::getGroupId, groupId);
        List<FileAttach> fileAttachList = attachService.list(queryWrapper);
        return ApiResult.success(fileAttachList);
    }

    @PostMapping()
    public ApiResult<FileAttach> postAttach(@RequestParam() MultipartFile file, @RequestParam(required = false) Long groupId) throws IOException {
        FileAttach fileAttach = attachService.saveAttachByGroupId(file, groupId);
        return ApiResult.success(fileAttach);
    }

    @DeleteMapping("{id}")
    public ApiResult<FileAttach> deleteAttach(@PathVariable long id) throws FileNotFoundException {
        FileAttach fileAttach = attachService.removeAttachById(id);
        return ApiResult.success(fileAttach);
    }

    @GetMapping("download/{id}")
    public void downloadAttach(@PathVariable long id) throws IOException {
        FileAttach fileAttach = attachService.getById(id);
        String groupPath = attachService.getGroupPath(fileAttach.getGroupId());
        File file = new File(groupPath + fileAttach.getName());

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileAttach.getName());

        OutputStream os  = response.getOutputStream();
        os.write(FileUtil.readBytes(file));
    }

}
